package cn.king.springframework.beans.factory.support;



import cn.king.springframework.beans.factory.DisposableBean;
import cn.king.springframework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {
    private Map<String,Object> singletonObjectMap = new HashMap<>();
    private final Map<String, DisposableBean> disposableBeans = new LinkedHashMap<>();

    protected static final Object NULL_OBJECT = new Object();

    @Override
    public Object getSingleton(String beanName) {
        return singletonObjectMap.get(beanName);
    }

    @Override
    public void registrySingleton(String beanName, Object singletonObject){
        singletonObjectMap.put(beanName,singletonObject);
    }
    public void registerDisposableBean(String beanName,DisposableBean bean){
        disposableBeans.put(beanName,bean);

    }

    public void destroySingletons(){
        Set<String> keySet = this.disposableBeans.keySet();
        Object[] disposableBeanNames = keySet.toArray();
        for(int i = disposableBeanNames.length - 1;i >= 0;i--){
            Object beanName = disposableBeanNames[i];
            DisposableBean disposableBean = disposableBeans.remove(beanName);
            try {
                disposableBean.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
